package controllers;

import java.lang.reflect.InvocationTargetException;

import models.Users;

import org.apache.commons.lang.StringUtils;

import play.Logger;
import play.cache.Cache;
import play.mvc.After;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.Scope;
import play.mvc.Scope.Session;

import com.etaoking.commons.BeanUtilsEx;
import com.etaoking.commons.Contants;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.User;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.UserGetResponse;

/**
 * 登陆验证控制
 * 
 * @author liucf
 * 
 */
public class AdminController extends Controller {

	@Before(unless={"acceptLogin","logout","putUserInfo","login"})
	public static void validator() {
		System.out.println("currentThread:" + Thread.currentThread().getId());
		if (Contants.UserInfo.current() == null) {
			redirect(("http://container.api.taobao.com/container?appkey=" + Contants.appKey));
		}
	}

	@After
	public static void putUserInfo() {
		if(Contants.UserInfo.current()!=null)
			session.put("userNick", Contants.UserInfo.current().getNick());
	}

	public static void acceptLogin(String top_session) {

		TaobaoClient client = new DefaultTaobaoClient(Contants.url,
				Contants.appKey, Contants.secret);
		UserGetRequest req = new UserGetRequest();
		req.setFields("user_id,nick,seller_credit");
		try {
			UserGetResponse response = client.execute(req, top_session);
			System.out.println(response.getErrorCode());
			if (response.getErrorCode() == null) {
				User user = response.getUser();
				Users newUser = new Users();
				newUser.sessionKey = top_session;
				BeanUtilsEx.copyProperties(newUser, user);
				Contants.UserInfo.put(newUser);
			} else if (response.getErrorCode().equals("27")) {
				Logger.info("无效的SessionKey!");
				login();
			} else {
				Logger.error("调用淘宝接口出错!错误代码("
						+ response.getErrorCode()
						+ "),错误码一览表:http://open.taobao.com/doc/detail.htm?id=114");
			}
			TradeAction.index();
		} catch (ApiException e) {
			Logger.error("接收淘宝返回的sessionKey出错!", e);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public static void logout() {
		if (Contants.UserInfo.current() != null) {
			Logger.info(Contants.UserInfo.current().getNick() + "注销成功!");
			Contants.UserInfo.remove();
			session.remove("userNick");
		}
		Application.index(0);
	}

	public static void login() {
		redirect(("http://container.api.taobao.com/container?appkey=" + Contants.appKey));
	}
}
